package com.yzq.os.spider.v.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.yzq.os.spider.v.domain.QueryURL;
import com.yzq.os.spider.v.service.domain.QueryURLService;
import com.yzq.os.spider.v.service.domain.SearchEngineService;

/**
 * 搜索URL控制器，搜索URL是需要提交的抓取URL
 * @author 苑志强(xingyu_yzq@163.com)
 *
 */
@Controller
@RequestMapping("/queryurl")
public class QueryURLController {

	private static Logger logger = Logger.getLogger(QueryURLController.class);

	@Autowired
	private QueryURLService queryURLService;

	@Autowired
	private SearchEngineService searchEngineService;

	/**
	 * 获取指定搜索引擎需要处理的搜索URL,最大返回n条
	 * @param request
	 * @param engineId
	 * @param maxReturn
	 * @return
	 */
	@RequestMapping("/willdo/{engineId}_{maxReturn}")
	@ResponseBody
	public List<QueryURL> load(HttpServletRequest request, @PathVariable int engineId, @PathVariable int maxReturn) {
		String host = request.getRemoteHost();
		logger.info("From host:[" + host + "],engineId:[" + engineId + "],maxReturn:[" + maxReturn + "]");
		List<QueryURL> queryUrls = queryURLService.findWillDoFromDatabase(engineId, maxReturn);
		logger.info("To host:[" + host + "],engineId:[" + engineId + "],maxReturn:[" + maxReturn + "],return:[" + CollectionUtils.size(queryUrls) + "]");
		return queryUrls;
	}

	/**
	 * 跳转到搜索URL页面（根据formType不同执行不同动作）
	 * @param formType
	 * @return
	 */
	@RequestMapping("/form/{formType}")
	public ModelAndView form(@PathVariable String formType) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("engines", searchEngineService.findUIViews());
		model.put("formType", formType);
		return new ModelAndView("/admin/queryurl/form", model);
	}

	/**
	 * 删除搜索URL备份表数据
	 * @param searchEngineId
	 * @return
	 */
	@RequestMapping(value = "/deleteValid", method = RequestMethod.POST)
	public RedirectView deleteValidBakQueryUrls(int searchEngineId) {
		queryURLService.deleteValidBakQueryUrls(searchEngineId);
		logger.info("Delete bak query urls from for searchEngineId:[" + searchEngineId + "]");
		return new RedirectView("form/deleteValid");
	}

	/**
	 * truncate搜索URL运行表数据
	 * @param searchEngineId
	 * @return
	 */
	@RequestMapping(value = "/truncate", method = RequestMethod.POST)
	public RedirectView doTruncate(int searchEngineId) {
		queryURLService.truncate(searchEngineId);
		return new RedirectView("form/truncate");
	}

/**
 * 将备份表中的搜索URL同步到运行表中，准备执行抓取
 * @param searchEngineId
 * @return
 */
	@RequestMapping(value = "/initValid", method = RequestMethod.POST)
	public RedirectView initValidBakQueryUrls(int searchEngineId) {
		queryURLService.initValidBakQueryUrls(searchEngineId);
		return new RedirectView("form/initValid");
	}

	/**
	 * 从搜索URL备份表中获取第一条搜索URL,用来执行排错测试
	 * @param searchEngineId
	 * @return
	 */
	@RequestMapping(value = "/firstValidPostUrl/{searchEngineId}")
	@ResponseBody
	public String findFirstValidBakQueryUrl(@PathVariable int searchEngineId) {
		List<String> postUrls = queryURLService.findFirstValidBakQueryUrl(searchEngineId, 1);
		if (CollectionUtils.isNotEmpty(postUrls)) {
			return postUrls.get(0);
		} else {
			return "not have post url in valid back table. need check.";
		}
	}
}
